package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jndi.JndiFactory;

import models.User;

public class UserDaoImpl implements UserDao {

	final JndiFactory jndi = JndiFactory.getInstance();

	@Override
	public List<User> list() {

		List<User> userList = new ArrayList<>();
		Connection connection = null;

		try {
			connection = jndi.getConnection("jdbc/waiDatenbank");

			PreparedStatement ps = connection
					.prepareStatement("SELECT id, username, password, cameras FROM users");
			ResultSet rs = ps.executeQuery();

			while (rs.next()) {
				User user = new User();
				user.setId(rs.getLong("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setCameras(rs.getString("cameras"));
				userList.add(user);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JndiFactory.closeConnection(connection);
		}

		return userList;
	}

	@Override
	public User getUser(Long id) {

		User user = null;
		Connection connection = null;

		try {
			connection = jndi.getConnection("jdbc/waiDatenbank");

			PreparedStatement ps = connection
					.prepareStatement("SELECT id, username, password, cameras FROM users WHERE id=?");
			ps.setLong(1, id);
			ResultSet rs = ps.executeQuery();

			if(rs.next()) {
				user = new User();
				user.setId(rs.getLong("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setCameras(rs.getString("cameras"));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JndiFactory.closeConnection(connection);
		}

		return user;
	}

}
